package com.m4f.fse.web.servlets;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.List;
import java.util.Collections;
import java.util.Enumeration;
import java.util.logging.Logger;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.m4f.fse.components.mergers.impl.GsaMerger;
import com.m4f.fse.components.impl.BaseSearchEngine;
import com.m4f.fse.components.impl.GsaSearchEngine;
import com.m4f.fse.components.SearchStack;
import com.m4f.fse.components.fitters.impl.GsaFitter;
import com.m4f.fse.utils.StackTraceUtil;
import com.m4f.fse.service.ObjetifyEngineService;

public class SearchServlet extends HttpServlet {
	
	private static final Logger LOGGER = Logger.getLogger(SearchServlet.class.getName());
	
	public void doGet(HttpServletRequest req, 
			HttpServletResponse resp) throws IOException {
		SearchStack stack = this.initStack();
		byte[] content = null;
		try {
			content = stack.search(this.parseParams(req));
		} catch(Exception e) {
			LOGGER.severe(StackTraceUtil.getStackTrace(e));
		}
		resp.setContentType("text/xml; charset=ISO-8859-1");
		resp.getOutputStream().write(content);
	}
	
	private SearchStack initStack() {
		ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
		ObjetifyEngineService engineService = context.getBean(ObjetifyEngineService.class);
		SearchStack stack = new SearchStack(new GsaMerger(), new GsaFitter());	
		for(Iterator<GsaSearchEngine> it = engineService.list(GsaSearchEngine.class); it.hasNext();) {
			stack.addEngine(it.next());
		}
		return stack;
	}
	
	private Map<String, String> parseParams(HttpServletRequest req) {
		Map<String, String> params = new HashMap<String, String>();
		List<String> requestParameterNames = 
			 Collections.list((Enumeration<String>)req.getParameterNames());
		for(String paramName : requestParameterNames) {
			params.put(paramName, req.getParameter(paramName));
		}
		return params;
	}
	
}